package com.llcbenwu.authentication;

import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.llcbenwu.config.LoginType;
import com.llcbenwu.config.SecurityProperies;
import com.llcbenwu.config.SimpleResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 失败处理器
 * @author lilinchun
 * @date 2021/10/25 0025 19:43
 */
@Component("llcAuthentiationFailHandler")
@Slf4j
//public class llcAuthentiationFailHandler implements AuthenticationFailureHandler {
public class llcAuthentiationFailHandler extends ExceptionMappingAuthenticationFailureHandler {  //spring自带原生


    @Autowired
    private ObjectMapper objectMapper;




    /**
     * 登录失败位置
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException, ServletException {

        log.info("登录失败");
        if(LoginType.JSON.equals(SecurityProperies.LOGINTYPE)) {
            //将封装的信息以json的格式返回
            httpServletResponse.setStatus(HttpStatus.HTTP_INTERNAL_ERROR);
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            //只返回错误的登录信息
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(e.getMessage())));
        }else {
            super.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
        }
    }
}
